from flask import Blueprint, request, jsonify
from app.models import db
from app.models.group import Group
from app.utils.auth import require_permission

groups_bp = Blueprint('groups', __name__)

@groups_bp.route('', methods=['GET'])
@require_permission('group.view')
def get_groups():
    """获取分组列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        search = request.args.get('search', '')
        
        query = Group.query.filter_by(is_active=True)
        
        if search:
            query = query.filter(Group.name.contains(search))
        
        pagination = query.paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        return jsonify({
            'groups': [group.to_dict() for group in pagination.items],
            'total': pagination.total,
            'pages': pagination.pages,
            'current_page': page
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@groups_bp.route('', methods=['POST'])
@require_permission('group.create')
def create_group():
    """创建分组"""
    try:
        data = request.get_json()
        
        if not data.get('name'):
            return jsonify({'error': '分组名称不能为空'}), 400
        
        # 检查分组名是否已存在
        if Group.query.filter_by(name=data['name']).first():
            return jsonify({'error': '分组名称已存在'}), 400
        
        group = Group(
            name=data['name'],
            description=data.get('description', '')
        )
        
        db.session.add(group)
        db.session.commit()
        
        return jsonify({'group': group.to_dict()}), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@groups_bp.route('/<int:group_id>', methods=['PUT'])
@require_permission('group.edit')
def update_group(group_id):
    """更新分组"""
    try:
        group = Group.query.get_or_404(group_id)
        data = request.get_json()
        
        # 检查分组名是否已被其他分组使用
        if 'name' in data and data['name'] != group.name:
            if Group.query.filter_by(name=data['name']).first():
                return jsonify({'error': '分组名称已存在'}), 400
            group.name = data['name']
        
        if 'description' in data:
            group.description = data['description']
        if 'is_active' in data:
            group.is_active = data['is_active']
        
        db.session.commit()
        
        return jsonify({'group': group.to_dict()}), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@groups_bp.route('/<int:group_id>', methods=['DELETE'])
@require_permission('group.delete')
def delete_group(group_id):
    """删除分组"""
    try:
        group = Group.query.get_or_404(group_id)
        
        # 检查是否有用户关联到此分组
        if group.users:
            return jsonify({'error': '该分组下还有用户，无法删除'}), 400
        
        db.session.delete(group)
        db.session.commit()
        
        return jsonify({'message': '分组删除成功'}), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500
